package com.zxj.netty.zookeeper;

import com.google.common.collect.Lists;
import com.zxj.netty.client.ChannelManager;
import com.zxj.netty.client.RpcClient;
import com.zxj.netty.common.RpcConstants;
import io.netty.channel.ChannelFuture;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.util.List;
import java.util.Set;

public class ZookeeperFactory {
    // 注册中心根节点
    public static final String ROOT = "/netty/";
    // 缓存远程服务ip，用于节点变更时重连所有节点
    private static CuratorFramework client = null;
    public static CuratorFramework getZookeeperClient() {
        if (client == null) {
            // 间隔1s重连,重试3次
            RetryPolicy policy = new ExponentialBackoffRetry(1000, 3);
            client = CuratorFrameworkFactory.newClient(RpcConstants.REGISTRY_ADDR, policy);
            client.start();
        }
        return client;

    }

    public static void subscribe() throws Exception {
        Set<String> systems = ChannelManager.SYSTEMS;
        for (String sys : systems) {
            String path = ROOT + sys;
            List<String> paths = getZookeeperClient().getChildren().forPath(path);

            List<ChannelFuture> channelFutures = Lists.newArrayList();
            for (String p : paths) {
                ChannelFuture future = RpcClient.connect(p.split("#")[0]);
                channelFutures.add(future);
            }
            ChannelManager.add(sys, channelFutures);
        }
    }

    public static void main(String[] args) throws Exception {
        CuratorFramework curatorFramework = getZookeeperClient();
        curatorFramework.create().creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL)
                .forPath(ZookeeperFactory.ROOT + "serviceA" + "/" + "192.168.1.12" + "#");
    }

    public static void watch() throws Exception {
        Set<String> systems = ChannelManager.SYSTEMS;
        for (String sys : systems) {
            getZookeeperClient().getChildren().usingWatcher(
                    new ServerWatcher()).forPath(ROOT + sys);
        }
    }

}
